package com.qs.javame.thread.think;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 问题：如何实现两个线程交替打印奇偶数？
 * <p>
 * 方案一：使用synchronized实现两个线程交替打印奇偶数
 */
public class TestDemo {

    private int MAX_NUM = 10;

    public static void main(String[] args) {
        TestDemo testDemo = new TestDemo();

        Thread thread = new Thread(testDemo::printEven, "thread");
        Thread thread2 = new Thread(testDemo::printOdd, "thread2");

        thread.start();
        thread2.start();
    }


    //打印奇数
    public synchronized void printOdd() {
        for (int i = 1; i <= MAX_NUM; i += 2) {
            try {
                System.out.println(Thread.currentThread().getName() + "-" + i);
                TimeUnit.SECONDS.sleep(1);
                //当输出最后一个奇数时，线程结束
                this.notify();
                if (i < MAX_NUM - 1) {
                    this.wait();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //打印偶数
    public synchronized void printEven() {
        for (int i = 0; i <= 10; i += 2) {
            try {
                System.out.println(Thread.currentThread().getName() + "-" + i);
                TimeUnit.SECONDS.sleep(1);
                //输出最后一个偶数，线程结束
                this.notify();
                if (i < MAX_NUM) {
                    this.wait();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


/**
 * 方案2：使用CAS实现两个线程交替打印奇偶数
 */
class Solution2 {

    private static int MAX_NUM = 10;

    private volatile boolean isSwitch = false;

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public static void main(String[] args) {
        Solution2 solution2 = new Solution2();
        Thread thread = new Thread(solution2::printEven);
        Thread thread2 = new Thread(solution2::printOdd);
        thread.start();
        thread2.start();
    }


    //输出偶数
    public void printEven() {
        Thread current = Thread.currentThread();
        while (atomicInteger.get() < MAX_NUM) {
            if (!isSwitch && atomicInteger.get() % 2 == 0) {
                System.out.println(current.getName() + "--" + atomicInteger.getAndIncrement());
            }

            //切换状态，让奇数继续输出
            isSwitch = true;
        }
    }


    //输出奇数
    public void printOdd() {
        Thread current = Thread.currentThread();
        while (atomicInteger.get() < MAX_NUM) {
            if (isSwitch && atomicInteger.get() % 2 == 1) {
                System.out.println(current.getName() + "--" + atomicInteger.getAndIncrement());
            }

            //更改状态，让偶数继续输出
            isSwitch = false;
        }
    }
}

/**
 * 方案3：使用JUC下的重入锁实现两个线程间隔打印奇偶数
 */
class Solution3 {

    private static int MAX_NUM = 10;

    //重入锁
    private ReentrantLock lock = new ReentrantLock();
    //创建condition对象，使用condition.await()/signal()，等待唤醒机制
    private Condition condition = lock.newCondition();

    public static void main(String[] args) {
        Solution3 solution3 = new Solution3();

        Thread evenThread = new Thread(solution3::printEven);
        Thread oddThread = new Thread(solution3::printOdd);

        evenThread.start();
        oddThread.start();
    }


    //打印输出偶数
    public void printEven() {
        //不要将获取锁的过程写在try块中，因为如果在获取锁时发生了异常，异常抛出的同时会造成锁无故释放。
        lock.lock();
        try {
            Thread current = Thread.currentThread();
            for (int i = 0; i < MAX_NUM; i += 2) {
                System.out.println(current.getName() + "--" + i);
                condition.signal();

                //输出最后一个偶数，线程退出
                if (i == MAX_NUM) {
                    break;
                }

                condition.await();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //打印输出奇数
    public void printOdd() {
        lock.lock();
        Thread currentThread = Thread.currentThread();
        try {
            for (int i = 1; i < MAX_NUM; i += 2) {
                System.out.println(currentThread.getName() + "-" + i);
                condition.signal();

                //输出最后一个偶数，线程退出
                if (i == MAX_NUM - 1) {
                    break;
                }

                condition.await();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}